from threading import Thread
import socket
import sys

HOST = ''   # Symbolic name meaning the local host
PORT = 24069    # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print('Socket created')
try:
    s.bind((HOST, PORT))
except socket.error:
    print('Bind failed')
    sys.exit()
print('Socket bind complete')
s.listen(1)
print('Socket now listening')


def socket_command_parse(sock, data):
    print(data)


def socket_loop(sock):
    while True:
        # RECEIVE DATA
        data = sock.recv(1024)
        if len(data) < 1: break
        socket_command_parse(data.decode('utf-8'))
        sock.send(data)
    print('Disconnect ', sock.getpeername())
    sock.close()

while True:
    # Accept the connection once (for starter)
    (conn, addr) = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))
    stored_data = ''

    t = Thread(target=socket_loop, args=(conn,))
    t.start()

s.close()  # When we are out of the loop, we're done, close
